package com.cxy.utils;


import com.alibaba.fastjson.JSONObject;
import com.cxy.context.BaseContext;
import com.cxy.result.Result;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Slf4j
@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    @Override
    //request用来获取请求参数,response用来返回响应结果
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 获取请求参数都是用 HttpServletRequest和HttpServletResponse 来获取请求参数所以要将request和response进行强转为HttpServletRequest和HttpServletResponse
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;



        //1.获取url
        String url = request.getRequestURL().toString();
        log.info("url为:{}",url);
//        boolean check=check(urls,url);
        if (url.contains("login")||url.contains("email")||url.contains("reset")
                ||url.contains("/doc.html")||url.contains("/webjars/**")||url.contains("/swagger-resources")||url.contains("/v2/api-docs")){
            //如果有使用chain放行
            log.info("登陆操作放行");
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }

        //3.获取请求头中的令牌
        String jwt = request.getHeader("token");

        //判断令牌是否存在
        if (jwt==null||jwt==" "){
            Result error = Result.error("NOT_LOGIN");
            //要向前端返回一个json格式的数据,但这并不是controller类
            //所以要手动转换成Json------这里用到了阿里巴巴fastJSON
            String notLogin = JSONObject.toJSONString(error);
            //最后响应给浏览器
            response.getWriter().write(notLogin);
            return;
        }
        //5.解析token如果解析失败返回错误结果
        try {
            Claims claims = JwtUtils.parseJWT(jwt);
            //登录成功后获取当前用户的id
            Long userId = Long.valueOf(claims.get("id").toString());
            log.info("当前员工id:",userId);
            BaseContext.setCurrentId(userId);
        }catch (Exception e){
            e.printStackTrace();
            Result error = Result.error("NOT_LOGIN");
            //要向前端返回一个json格式的数据,但这并不是controller类
            //所以要手动转换成Json------这里用到了阿里巴巴fastJSON
            String notLogin = JSONObject.toJSONString(error);
            //最后响应给浏览器
            response.getWriter().write(notLogin);
            return;
        }
        //令牌合法
        filterChain.doFilter(servletRequest,servletResponse);
    }

}
